#!/usr/bin/env python
# -*- coding: utf-8 -*-
r"""
文件名称: sidebar_api.py
完整存储路径: backend/api/sidebar_api.py
功能说明:
    提供侧边栏菜单数据 API 接口，返回 JSON 格式的菜单数据。
    根据用户具体权限动态过滤菜单，实现细粒度权限控制。
使用说明:
    通过 GET 请求访问 /api/menu 获取菜单数据，需要JWT认证。
"""

from flask import Blueprint, jsonify, request
from flask_jwt_extended import jwt_required, get_jwt_identity, get_jwt
from backend.models.user import User
from backend.models.permission import Permission

sidebar_api = Blueprint('sidebar_api', __name__)

# 完整菜单数据结构（包含权限要求）
complete_menu_data = [
    {
        "title": "欢迎登录",
        "link": "/",
        "icon": "bi-house-door",
        "sub_menu": [],
        "required_permission": None  # 无权限要求，所有用户可见
    },
    {
        "title": "系统首页", 
        "link": "index",
        "icon": "bi-house-door",
        "sub_menu": [],
        "required_permission": None  # 无权限要求，所有用户可见
    },
    {
        "title": "数据管理",
        "link": "#",
        "icon": "bi-folder",
        "required_permission": None,  # 父菜单无权限要求，由子菜单控制
        "sub_menu": [
            {
                "title": "批量数据导入", 
                "link": "/import", 
                "icon": "bi-upload",
                "required_permission": "student:import"
            },
            {
                "title": "数据录入编辑", 
                "link": "/student-complete-record", 
                "icon": "bi-person-lines-fill",
                "required_permission": "student:edit"
            },
            {
                "title": "干预操作记录", 
                "link": "/interventions", 
                "icon": "bi-file-earmark-text",
                "required_permission": "intervention:read"
            },
            {
                "title": "电话随访记录", 
                "link": "/phone-followup", 
                "icon": "bi-telephone",
                "required_permission": "followup:read"
            },
            {
                "title": "视力数据录入", 
                "link": "/vision-records", 
                "icon": "bi-eye",
                "required_permission": "vision:read"
            }
        ]
    },
    {
        "title": "数据查询",
        "link": "query",
        "icon": "bi-search",
        "sub_menu": [],
        "required_permission": "student:read"
    },
    {
        "title": "统计分析",
        "link": "#",
        "icon": "bi-bar-chart-line",
        "required_permission": None,  # 父菜单无权限要求，由子菜单控制
        "sub_menu": [
            {
                "title": "统计报表", 
                "link": "report", 
                "icon": "bi-pie-chart",
                "required_permission": "report:read"
            },
            {
                "title": "图表展示", 
                "link": "chart", 
                "icon": "bi-graph-up",
                "required_permission": "chart:export"
            }
        ]
    },
    {
        "title": "系统管理",
        "link": "#",
        "icon": "bi-gear",
        "required_permission": "system:manage",  # 需要系统管理权限才能看到整个系统管理菜单
        "sub_menu": [
            {
                "title": "用户管理", 
                "link": "/user-management", 
                "icon": "bi-person",
                "required_permission": "user:read"
            },
            {
                "title": "角色管理", 
                "link": "/role-management", 
                "icon": "bi-people",
                "required_permission": "role:read"
            },
            {
                "title": "权限管理", 
                "link": "/permission-management", 
                "icon": "bi-shield-lock",
                "required_permission": "permission:read"
            },
            {
                "title": "文档管理", 
                "link": "/document-management", 
                "icon": "bi-file-earmark-text",
                "required_permission": "system:manage"
            },
            {
                "title": "通知公告", 
                "link": "/notification-management", 
                "icon": "bi-bell",
                "required_permission": "system:manage"
            },
            {
                "title": "用户反馈", 
                "link": "/feedback-management", 
                "icon": "bi-chat-dots",
                "required_permission": "feedback:read"
            },
            {
                "title": "医生交流", 
                "link": "/doctor-consultation", 
                "icon": "bi-chat-left-dots",
                "required_permission": "medical_consult:read"
            },
            {
                "title": "操作日志", 
                "link": "/operation-log", 
                "icon": "bi-journal-text",
                "required_permission": "log:read"
            }
        ]
    }
]

def get_user_permissions(user_id):
    """获取用户的所有权限码列表"""
    try:
        user = User.query.get(user_id)
        if not user:
            return []
        
        # 获取用户的所有权限
        permissions = set()
        for role in user.roles:
            for permission in role.permissions:
                permissions.add(permission.code)
        
        return list(permissions)
    except Exception as e:
        print(f"获取用户权限错误: {e}")
        return []

def filter_menu_by_permissions(menu_data, user_permissions):
    """根据用户权限过滤菜单"""
    filtered_menu = []
    
    for menu_item in menu_data:
        # 检查菜单项是否需要权限
        required_permission = menu_item.get('required_permission')
        
        # 创建菜单项副本
        filtered_item = {
            "title": menu_item["title"],
            "link": menu_item["link"], 
            "icon": menu_item["icon"],
            "sub_menu": []
        }
        
        # 处理子菜单
        if menu_item.get("sub_menu"):
            filtered_submenu = []
            for sub_item in menu_item["sub_menu"]:
                sub_required_permission = sub_item.get('required_permission')
                
                # 如果子菜单不需要权限或用户有该权限，则保留
                if sub_required_permission is None or sub_required_permission in user_permissions:
                    filtered_submenu.append({
                        "title": sub_item["title"],
                        "link": sub_item["link"],
                        "icon": sub_item["icon"]
                    })
            
            # 只有在以下情况下才保留父菜单:
            # 1. 父菜单本身需要权限且用户有该权限
            # 2. 父菜单不需要权限但有可见的子菜单
            if required_permission is not None:
                # 父菜单需要权限
                if required_permission in user_permissions:
                    filtered_item["sub_menu"] = filtered_submenu
                    filtered_menu.append(filtered_item)
            else:
                # 父菜单不需要权限，但需要有可见的子菜单才显示
                if filtered_submenu:
                    filtered_item["sub_menu"] = filtered_submenu
                    filtered_menu.append(filtered_item)
        else:
            # 没有子菜单的情况
            if required_permission is None or required_permission in user_permissions:
                filtered_menu.append(filtered_item)
    
    return filtered_menu

@sidebar_api.route('/api/menu')
@jwt_required()
def get_menu():
    """
    根据用户权限返回侧边栏菜单 JSON 数据.
    Returns:
        JSON: 根据用户权限过滤的菜单数据列表.
    """
    try:
        # 获取当前用户ID
        current_user_id = get_jwt_identity()
        
        # 获取用户权限列表
        user_permissions = get_user_permissions(current_user_id)
        
        # 根据权限过滤菜单
        filtered_menu = filter_menu_by_permissions(complete_menu_data, user_permissions)
        
        return jsonify(filtered_menu)
        
    except Exception as e:
        print(f"菜单API错误: {e}")
        # 如果出现异常，返回基础菜单（安全起见）
        basic_menu = [
            {
                "title": "欢迎登录",
                "link": "/",
                "icon": "bi-house-door",
                "sub_menu": []
            },
            {
                "title": "系统首页",
                "link": "index", 
                "icon": "bi-house-door",
                "sub_menu": []
            }
        ]
        return jsonify(basic_menu)
